在我們之前提到的Execution Context,都會執行一個被稱為"Hoisting的步驟"。


而今天就要來複習hoisting ~
JavaScript Hoisting refers to the process whereby the interpreter allocates memory for variable and function declarations prior to execution of the code.
Declarations that are made using
varare initialized with a default value ofundefined. Declarations made using let and const are not initialized as part of hoisting.
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms | MDN
而Hoisting執行的行為是: 電腦會先分配記憶體給var和function Declaration。
所以我們要來了解這個行為的影響,
首先,看看let,const和var的例子:
console.log(x); // ReferenceError: x is not defined
let x = 100;
console.log(x); // ReferenceError: x is not defined
const x = 100;
如果是用let或const宣告的變數,不會被提前分配記憶體,
就不會提升initialize這個行為,
因此,如果在宣告變數前就使用變數,那麼就會彈出ReferenceError,告訴你變數還未被定義。
console.log(x); // output: undefined
var x = 100;
然而被用var宣告的變數,這裡的console會告訴你undefined。
也就是說,對瀏覽器而言,這個變數已經被初始化過了。
(瀏覽器知道這個變數存在,只是尚未被賦值。)
使用 Function Declaration 也會被hoisting:
functionDeclaration(); // output: 100
function functionDeclaration(){
console.log(100);
}
要注意的是,執行Function Expression就不會被進行hoisting:
functionExpression(); // ReferenceError: functionExpression is not defined
const functionExpression = () => {
console.log(100);
}
而上面是最粗淺的解釋,如果想要深入理解很推薦這篇文章:
我知道你懂 hoisting,可是你了解到多深?
【如果內文有誤還請不吝指教>< 也謝謝閱覽至此的各位:D】
-----正文結束-----
今天比較忙所以打的比較簡單,但之前有看過整理的很好的文章,就也放進來了。